﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

using Microsoft.ApplicationBlocks.Updater;

using NUnit.Framework;

namespace DotUpdater.Test
{
    [TestFixture]
    public class TestUpdater
    {
        private string path;
        private Updater updater;

        #region SetUp/TearDown

        [SetUp]
        public void SetUp()
        {
            path = Utility.TempBasePath;
            string[] files = ExtractFiles(path);
            Assert.Greater(files.Length, 0);

            updater = new Updater(null, files[0]);
        }

        [TearDown]
        public void TearDown()
        {
            if (updater != null)
            {
                (updater as IDisposable).Dispose();
            }
        }

        private static string[] ExtractFiles(string pathTo)
        {
            string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;

            string[] names = Assembly.GetExecutingAssembly().GetManifestResourceNames();

            string fileName = "update.rss";
            Stream resourceStream = Assembly.GetExecutingAssembly().
                GetManifestResourceStream(assemblyName + ".files." + fileName);

            if (resourceStream == null)
            {
                throw new Exception("Could not locate embedded resource '" + fileName + "' in assembly '" + assemblyName + "'");
            }

            string fullFileName = Path.Combine(pathTo, fileName);

            Stream fstream = new FileStream(fullFileName, FileMode.Create);
            while (resourceStream.Position < resourceStream.Length) // Sorry guys, I'm tired, and who ever cares.
            {
                fstream.WriteByte((byte)resourceStream.ReadByte());
            }
            resourceStream.Close();
            fstream.Close();
            return new[] { fullFileName };
        }

        #endregion SetUp/TearDown

        //[Test]
        public void TestWaitForExitProcess()
        {
        }

        [Test]
        public void TestCheckForUpdates()
        {
            updater.CheckForUpdates();
            UpdaterTask task = updater.CreateFromFeed();
            Assert.IsNotNull(task);
        }
    }
}
